<template>
  <div class="tinymce-box" v-loading="editLoading">
    <div :id="id"></div>
  </div>
  <kva-upload-dialog ref="imgUploadDialogRef" @success="handleUploadImgSuccess"></kva-upload-dialog>
</template>
<script  setup>
import tinymce from 'tinymce/tinymce'; //tinymce核心文件
import 'tinymce/models/dom'; // 引入dom模块。从 Tinymce6，开始必须有此模块导入
import 'tinymce/themes/silver'; //默认主题
import 'tinymce/icons/default'; //引入编辑器图标icon，不引入则不显示对应图标
/* 引入编辑器插件
 * 位于 ./node_modules/tinymce/plugins 目录下，版本不同，插件会有所差异。根据自己版本来导入，若不存在的，不能导入，会报错。
 */
import 'tinymce/plugins/advlist'; //高级列表
import 'tinymce/plugins/autolink'; //自动链接
import 'tinymce/plugins/directionality'; //文字方向
import 'tinymce/plugins/fullscreen'; //全屏
import 'tinymce/plugins/insertdatetime'; //插入日期时间
import 'tinymce/plugins/link'; //超链接
import 'tinymce/plugins/lists'; //列表插件
import 'tinymce/plugins/preview'; //预览
import 'tinymce/plugins/image'; //图片处理
import 'tinymce/plugins/media'; //图片处理
import 'tinymce/plugins/quickbars'; //快速工具栏
import 'tinymce/plugins/searchreplace'; //查找替换
import 'tinymce/plugins/table'; //表格
import '@/components/tinymce/custom/formatpainter/plugin.min.js';
import '@/components/tinymce/custom/plugin.js';

const props = defineProps({
  id:{
    type:String,
    default:"tinydemo"
  },
  articleId:{
    type:Number,
    default:0
  },
  flag:{
    type:Boolean,
    default:false
  },
  content:{
    type:String,
    default:""
  },
  linkcard:{
    type:Boolean,
    default:false
  },
  linkarea:{
    type:Boolean,
    default:false
  },
  height:{
    type:Number,
    default:300
  },
  showmedia:{
    type:Boolean,
    default:true
  }
})
var menubar = true
var toolbar = 'image media custom-image undo redo bold italic underline strikethrough formatpainter bullist numlist link alignleft aligncenter alignright listprops styleselect forecolor backcolor styles fontsize fullscreen custom-area custom-card'
var menu = {
  file: {title: '文件', items: 'newdocument'},
  edit: {title: '编辑', items: 'undo redo | cut copy paste pastetext | selectall'},
  insert: {title: '插入', items: 'custom-image  link |  hr'},
  view: {title: '查看', items: 'visualaid'},
  format: {title: '格式', items: 'bold italic underline strikethrough superscript subscript | formats | removeformat'},
  table: {title: '表格', items: 'inserttable tableprops deletetable | cell row column'},
  tools: {title: '工具', items: 'spellchecker code'},
}
if(!props.showmedia){
  toolbar = 'image media custom-image  undo redo bold italic underline strikethrough formatpainter bullist numlist link alignleft aligncenter alignright listprops styleselect forecolor backcolor styles fontsize  fullscreen custom-area custom-card'
  menu = ""
  menubar = false
}
const emits = defineEmits(["update:content","success"])
const videoUploadDialogRef = ref({});
const imgUploadDialogRef = ref({});
const editorRef = ref({})
const editLoading = ref(true)
const handleInitEditor = ()=>{
  tinymce.init({
    selector: '#'+props.id,
    setup: function (editor) {
      editor.on('init', function (e) {
        editorRef.value = editor;
        editLoading.value = false;
        setTimeout(()=>{
          var querySelectAlls = document.querySelectorAll(".tox-toolbar__group")
          for(var i=0;i<querySelectAlls.length;i++){
            querySelectAlls[i].children[0].style.display = "none"
          }
        },300)
        // 监听父组件传递的content变化，更新编辑器内容
        editor.setContent(props.content)
        emits("success",editor)
      });


      editor.on("image_action",function(){
        imgUploadDialogRef.value.handleOpen()
      })

      editor.on("media_action",function(){
        alert("功能完善中....")
      })

      editor.on("input",function(){
        var content = tinymce.activeEditor.getContent();
        emits("update:content",content);
      })

      editor.on('paste', (e) => {
        var content = tinymce.activeEditor.getContent();
        localStorage.setItem("maya-tinymce-html",content)
        emits("update:content",content);
      })

      editor.on('ExecCommand', (e) => {
        var content = tinymce.activeEditor.getContent();
        emits("update:content",content);
      });

      // editor.ui.registry.addButton('custom-image', {
      //   text: '插入图片',
      //   // icon: '',
      //   tooltip: '插入卡片',
      //   onAction: function () {
      //     imgUploadDialogRef.value.handleOpen()
      //   },
      // })

      if(props.linkcard) {
        editor.ui.registry.addButton('custom-card', {
          text: '链接卡片',
          // icon: '',
          tooltip: '插入卡片',
          onAction: function () {
            var html = `<a class="content-file" href="/xxx.html" target="_blank" rel="noopener">
            <span class="content-file-filename">链接文本</span> </a>`
            editor.insertContent(html)
          },
        })
      }
      if(props.linkarea) {
        editor.ui.registry.addButton('custom-area', {
          text: '区域卡片',
          // icon: '',
          tooltip: '插入块',
          onAction: function () {
            var html = `<blockquote><p><strong>插入内容</strong></p></blockquote>`
            editor.insertContent(html)
          },
        })
      }

    },

    autosave_ask_before_unload: false,
    autosave_interval: '30s',
    autosave_prefix: '{path}{query}-{id}-',
    autosave_restore_when_empty: false,
    autosave_retention: '2m',
    language_url: '/langs/zh-Hans.js',
    language: 'zh-Hans',
    skin_url: '/skins/ui/oxide',
    content_css: ['/css/reset.css'],
    width:"100%",
    height: props.height, //编辑器高度
    object_resizing: false,
    menubar: menubar,
    toolbar_drawer: false,
    statusbar: false,  // 隐藏底部状态栏
    promotion: false, //Upgrade是否开启
    branding: false, //tiny技术支持信息是否显示
    plugins: 'fullscreen searchreplace autolink formatpainter directionality link  table image media  insertdatetime advlist lists custom-image custom-media', //使用image插件
    contextmenu: 'image',
    menu: menu,
    //toolbar: "undo redo |  formatselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists link unlink image table | removeformat | fullscreen"
    toolbar: toolbar,
    line_height_formats: '1 1.2 1.4 1.6 2', //行高
    font_size_formats: '12px 14px 16px 18px 20px 22px 24px 28px 32px 36px 48px 56px 72px', //字体大小
    font_family_formats: '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;'
  })
}

// 图片上传成功
const handleUploadImgSuccess = async (resp)=>{
  var baseimg = resp;
  var img = new Image()
  img.src = baseimg;
  img.onload = ()=>{
    const imgTagWithDirective = `<p class="imgbox"><img class="maya-img"  src="${baseimg}"  data-src="${baseimg}" /></p><p></p>`;
    editorRef.value.insertContent(imgTagWithDirective)
    imgUploadDialogRef.value.handleClose()
  }
}

const setHtml = (html)=>{
  tinymce.activeEditor.setContent(html)
}

const getHtml = () =>{
  return tinymce.activeEditor.getContent()
}
const handleClose=()=>{
  videoUploadDialogRef.value.handleClear()
}
onMounted(()=>{
  handleInitEditor()
})

defineExpose({
  setHtml,
  handleClose,
  videoUploadDialogRef,
  getHtml
})

</script>
<style scoped>
.tinymce-box {
  width: 100%;
}
</style>